#include <my_header.h>

int main(int argc,char *argv[])
{
    MYSQL* mysql=mysql_init(NULL);
    
    // Set character set to utf8mb4 to support Chinese characters
    mysql_options(mysql, MYSQL_SET_CHARSET_NAME, "utf8mb4");
    
    MYSQL *ret=mysql_real_connect(mysql,"localhost","admin","123654","test0",0,NULL,0);
    if(ret==NULL){
        printf("ERRO: %s\n",mysql_error(mysql));
        return -1;
    }
    
    // Execute query to ensure the connection uses UTF-8
    mysql_query(mysql, "SET NAMES 'utf8mb4'");
    
    char *sql1="select * from Student;";
    int  qret=mysql_query(mysql,sql1);
    if(qret!=0){
        printf("ERRO: %s\n",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *res=mysql_store_result(mysql);
    printf("total cols: %u, total rows: %lu\n",mysql_num_fields(res),mysql_num_rows(res));
    for(int i=0;i<mysql_num_rows(res);i++){
        MYSQL_ROW row=mysql_fetch_row(res);
        for(int j=0;j<mysql_num_fields(res);j++){
            printf("%s\t",row[j]);
        }
        printf("\n");
    }

    char name[256]={0};
    char birth[256]={0};
    char sex[30]={0};

    fgets(name,256,stdin);
    name[strlen(name)-1]='\0';

    fgets(birth,256,stdin);
    birth[strlen(birth)-1]='\0';

    fgets(sex,30,stdin);
    sex[strlen(sex)-1]='\0';
    printf("name=%s, birth=%s, sex=%s\n",name,birth,sex);

    char sql[1024]={0};
    // Fix the SQL syntax by ensuring correct comma placement
    sprintf(sql,"insert into Student (s_name,s_birth,s_sex) values ('%s','%s','%s')",name,birth,sex);
    printf("%s\n",sql);
    qret=mysql_query(mysql,sql);
    if(qret!=0){
        fprintf(stderr,"%s:%s\n","mysql_query",mysql_error(mysql));
        return -1;
    }

    mysql_store_result(mysql);
    sql1="select * from Student;";
     qret=mysql_query(mysql,sql1);
    if(qret!=0){
        printf("ERRO: %s\n",mysql_error(mysql));
        return -1;
    }
    res=mysql_store_result(mysql);
    printf("total cols: %u, total rows: %lu\n",mysql_num_fields(res),mysql_num_rows(res));
    for(int i=0;i<mysql_num_rows(res);i++){
        MYSQL_ROW row=mysql_fetch_row(res);
        for(int j=0;j<mysql_num_fields(res);j++){
            printf("%s\t",row[j]);
        }
        printf("\n");
    }
    mysql_close(mysql);
    return 0;
}
